package com.roy.netty.heatbeat;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.EventExecutorGroup;

/**
 * @author ：楼兰
 * @date ：Created in 2021/6/8
 * @description:
 **/

public class HeatbeatServerHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("读取消息："+msg);
        if ("heartbeat".equals(msg)) {
            ctx.writeAndFlush("heartbeat");
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            final IdleStateEvent event = (IdleStateEvent) evt;
            String eventType = null;
            if(IdleState.READER_IDLE.equals(event.state())){
                eventType="读空闲";
            }else if(IdleState.WRITER_IDLE.equals(event.state())){
                eventType="写空闲";
            }else if(IdleState.ALL_IDLE.equals(event.state())){
                eventType="读写空闲";
            }
            System.out.println(ctx.channel().remoteAddress() + "--发生超时事件--" + eventType);
            //如果发生空闲，就关闭通道
//            ctx.channel().close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生异常："+cause.getMessage());
    }
}
